<template>




	<div class="merak-container-has-aside" curPageName="7dsfds53461242187">
	
	
	
		  <div class="merak-aside"><treeNode @node-change="nodeChange" :parentTreeValue="parent_id"  treeLevel="3" :defTreeValue="org_id"></treeNode></div>
		  <div class="merak-card merak-container-has-search" v-waterMarker>
			<div >
			   
				<searchBar :close-plan="true"
			    :close-advanced="true"   ref="searchbar" placeholder="员工姓名 / 工号" :search_val=search_val @search-event="searchBarPost" v-model="searchform">
	
				<!-- 高级搜索弹出框 插槽-->
				<template #searchForm>
						<!--  高级搜索弹出框内容-->
						<div class="modal-content">
						<div class="modal-title">高级搜索</div>
	
						<div class="modal—body">
							<el-scrollbar height="100%">
							<div class="scrollbar-content">
								<!-- 已选参数 组件-->
								<selectedParams v-model="searchform" label="label" val="value" option-key="options"></selectedParams>
	
								<!-- 表单 -->
								<el-form :model="searchform" label-position="top" ref="ruleFormRef">
								<merakColapse :is-active="false">
									<template #header>基本信息</template>
	
									<el-row :gutter="20">
									<el-col :span="12">
										<el-form-item :label="searchform.org_company.label">
										<el-select style="width: 100%" v-model="searchform.org_company.value" placeholder="请选择..." clearable>
											<el-option
											v-for="option in searchform.org_company.options"
											:key="option"
											:label="option.label"
											:value="option.value"
											/>
										</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item :label="searchform.org_department.label">
										<el-select
											style="width: 100%"
											v-model="searchform.org_department.value"
											placeholder="请选择..."
											clearable
										>
											<el-option
											v-for="option in searchform.org_department.options"
											:label="option.label"
											:value="option.value"
											/>
										</el-select>
										</el-form-item>
									</el-col>
									</el-row>
	
									<el-row :gutter="20">
									<el-col :span="12">
										<el-form-item :label="searchform.job_nature.label">
										<el-select style="width: 100%" v-model="searchform.job_nature.value" placeholder="请选择..." clearable>
											<el-option
											:label="option.label"
											:value="option.value"
											v-for="option in searchform.job_nature.options"
											:key="option"
											/>
										</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item :label="searchform.status.label">
										<el-select style="width: 100%" v-model="searchform.status.value" placeholder="请选择..." clearable>
											<el-option
											:label="option.label"
											:value="option.value"
											v-for="option in searchform.status.options"
											:key="option"
											/>
										</el-select>
										</el-form-item>
									</el-col>
									</el-row>
								</merakColapse>
								</el-form>
								<!-- 表单 -->
							</div>
							</el-scrollbar>
						</div>
						<div class="modal-footer">
							<el-button type="default" @click="closeModal">取消</el-button>
							<el-button type="primary" @click="searchSubmitForm(ruleFormRef)">搜索</el-button>
							<el-button type="success" @click="showPlanModal">保存搜索方案</el-button>
						</div>
						</div>
						<!--  高级搜索弹出框内容-->
					</template>
					<!-- /高级搜索弹出框 插槽-->
	
	
					   
				</searchBar>
				</div>
		  <div class="merak-table-wrapper">
			<MerakXTable ref="tableRef" :columns-by-store="JSON.parse(JSON.stringify(state.columns))"
						:query-columns="handleQueryColumns" :query-data="handleQueryData" :params="state.params" 
						:column-min-width="120"
						row-key="user_id"
						:column-type="[ 'selection',{type: 'handle', width: 230, slot: 'handler' }]"
						:batches="[{text: '批量分配权限', color: 'green', type:'shareauth'}]"
						:batch-click="handleBatchClick">
	
	
						<template #handler="{ row }">
							<div>
								<el-button type="primary" link  @click="godetail(row)">修改权限 </el-button>
								<el-button type="primary" link  @click="openshare(row)">复制权限给 </el-button>
							</div>
						</template>

						
						<template #access_status_slots="{ row }">
							<div>

								<el-switch
									v-model="row.access_status"
									class="ml-2"
									inline-prompt
									style="--el-switch-on-color:#ff4949; --el-switch-off-color:  #13ce66"
									active-text="禁止"
									inactive-text="正常"
									@click="edit_access_status(row)"
								/>
							</div>
						</template>



						
	
	
					</MerakXTable>
		  </div>
		  </div>




		<el-dialog  modal-class="merak_modal"  v-model="shareDialog" title="I am the title" direction="rtl"  size="60%">
      <template #header>
        <div class="merak_modal_title">复制 <{{uid_name}}> 的权限给 </div>
      </template>
      <div class="personbox">
					<div class="treeL">
						<el-input placeholder="搜索" v-model="filterText">
						</el-input>
						<div class="personall">
							<div v-show="searchactive">
								<el-tree empty-text="sdsd" @node-click="treelabelClick" :data="persondata" show-checkbox
									@check-change="treechange_person" default-expand-all node-key="id" ref="personallTreeRef"
									highlight-current :filter-node-method="filterNode" :props="defaultProps">

									<!--                                <span class="custom-tree-node" slot-scope="{ node, data }">-->
									<!--                                    <span >{{ node.label }}</span>-->
									<!--                                   -->
									<!--                                </span>-->


								</el-tree>
							</div>


							<div v-if="searchactive == false">
								<el-checkbox-group v-model="searchchecked" class="searchPersonAll">
									<el-checkbox v-for="item in searchPersonData"
										:label="item.id">{{ item.label }}</el-checkbox>
								</el-checkbox-group>
							</div>




						</div>

					</div>

					<div class="treeR">
						<div class="treeRtit">

							<span v-if="personrightArr.length < 1">
								选择权限成员

							</span>
							<span v-else>
								已选择 · {{ personrightArr.length }}
							</span>

						
						</div>

						<div class="checkedpersons">
							<div class="checkedperson_ever" v-for="(item, index) in personrightArr">
								{{ item.label }}

								
									<Delete style="width: 1em; height: 1em; margin-right: 8px" @click="del_checkedpersons(personrightArr, index)"/>

							</div>
						</div>
					</div>




					
					
		</div>


      <template #footer>
        <el-button type="default" @click="closeperson">取消</el-button>
        <el-button type="primary"@click="identify_persons">确认</el-button>

      </template>
    </el-dialog>
		</div>




		
	
	</template>
	
	<script lang="ts" setup name="permissionAssignment">
		import { Plus, Edit, Delete, EditPen,CopyDocument } from '@element-plus/icons-vue';
	
		import { ref, reactive, onMounted, getCurrentInstance ,watch } from "vue";
	
		
		import searchBar from "@/components/SearchBar";
		import merakColapse from "@/components/merakColapse/index.vue";
		import selectedParams from "@/components/SearchBar/components/selectedParams.vue";
	
	
		import MerakXTable, { MerakXTableInstance, MerakXTableColumn, MerakXTableQuery } from "@/components/MerakXTable";
		import { moreConfirm, confirmWarningMsg, successMsg, warnMsg, failMsg, confirmSuccessMsg, delConfimMsg } from "@/utils/messageUtils";
		import { permissionAuthHeaderApi, permissionAuthListApi ,saveCopyAuthApi,editStatusApi} from "@/api/modules/permission";
		import treeNode from '@/views/personalManagement/a-components/oragnizationTree/index.vue';
		import { getLocationParams } from "@/utils/index";
		import router from "@/routers";
	
		import type { ElForm } from "element-plus";
		type FormInstance = InstanceType<typeof ElForm>;
		const leavesRef = ref < FormInstance > ();
	
		const { proxy } = getCurrentInstance();
	
	
		const tableRef = ref < MerakXTableInstance > ();
	
		const org_id=ref("")
		const parent_id=ref("")
		const lever_id=ref("")
		
	
	 
		const year=ref('0')

		const shareDialog = ref(false)
		

		//被参考用户uid
		const uid_origin=ref('');
		const uid_name=ref('');
		// 复制权限给
		const openshare = (row) => {
			// //console.log(row)
			shareDialog.value=true;
			uid_origin.value=row.user_id;
			uid_name.value=row.employee_name;

		}



		// 选人弹框
		const filterText=ref('');
		const searchactive=ref(true);
		const defaultProps=ref({ children: 'children', label: 'label' })
		const searchchecked=ref([])
		const searchPersonData=ref([])
		const personallTreeRef=ref()
		const personrightArr=ref([]);
		const oldchoose=ref([]);
		const identify_personsArr=ref([]);
		const postTreeData=ref([]);
	
	

		const access_right_modal=ref('0');


		//修改权限
		const edit_access_status=(row)=>{
			let post_access_status="";
			if (row.access_status == true) {
				post_access_status="0"
			}else{
				post_access_status="1"
			}

				editStatusApi({"user_id":row.user_id,"access_status":post_access_status}).then(res => {
					if (res.code == ResultEnum.SUCCESS) {
						successMsg('操作成功!');
					}else{
						failMsg(res.message);
						if (post_access_status == 0) {
							row.access_status=false;
						}else{
							row.access_status=true;
						}
						

					}
				})
		}

		let persondata=reactive([]);

		watch(filterText, (val) => {
			personallTreeRef.value!.filter(val)
		})

		const treelabelClick = (data, node, obj) => {
            //console.log(data, node, obj)
            //console.log(node.checked)
            //console.log(data.id)
            if (data.isUser) {
				//console.log("Ssss")
                if (node.checked) {
					//console.log("2222")
					//personallTreeRef.setChecked(data.id, false)
					//personallTreeRef.value!.setCheckedKeys([data.id], false)
					personallTreeRef.value.setChecked(data.id, false)
                } else {
					personallTreeRef.value.setChecked(data.id, true)
                   
					//personallTreeRef.value!.setCheckedKeys([data.id], true)
                }
            }
        }
		//选人搜索
		
        const filterNode = (value, data) => {
            if (!value) return true;
            var value = value.toLowerCase();
            var label = data.label.toLowerCase();
            return label.indexOf(value) !== -1;
        }
        //左侧选人修改
		
        const treechange_person = () => {
    
           personrightArr.value = personallTreeRef.value.getCheckedNodes(true, false);


            searchchecked.value = personallTreeRef.value.getCheckedKeys(true, false);

        }
        //右侧选人删除
        const del_checkedpersons = (arr, delid) => {
            //console.log(delid)
            var lkeys = personallTreeRef.value.getCheckedKeys(true, false);
            //console.log(lkeys)
            lkeys.splice(delid, 1)
            arr.splice(delid, 1)
            //console.log(lkeys)
			personallTreeRef.value.setCheckedKeys(lkeys);
            //  this.$refs.tree.setCheckedKeys([3,2,5]);
        }
        const del_arr = (_arr, thisindex) => {
            _arr.splice(thisindex, 1)
        }
		//确认提交选中人
		const copySubmit = () => {  
			saveCopyAuthApi({"uid_batch":postTreeData.value,"uid_origin":uid_origin.value}).then(res => {
				if (res.code == ResultEnum.SUCCESS) {
	
	
					successMsg(res.message);
	
					
				}else{
					failMsg(res.message);
				}
			})
		}
        //选人弹框确定点击
        const identify_persons = () => {
     
            const checkedarr = personallTreeRef.value.getCheckedNodes(true, false);
			//console.log(checkedarr)

			postTreeData.value=[];
			for (let index = 0; index < checkedarr.length; index++) {
				const element = checkedarr[index];
				postTreeData.value.push(element.id)
			}
			//console.log(postTreeData.value)
			shareDialog.value=false;
            resetChecked()
            filterText.value = '';

			copySubmit()



        }
		
        //关闭弹框
		const closeperson = () => {  
            filterText.value = '';
            shareDialog.value=false;
            resetChecked();
			Object.assign(persondata,JSON.parse(JSON.stringify(persondata)))
        }

		 // 清空选人
		 const resetChecked = () => {  
            personallTreeRef.value.setCheckedKeys([]);
        }













	
		//接收url参数
		const newUrl = new URL(window.location.href);
		let url_org_id = getLocationParams(newUrl.href,'org_id');
		org_id.value=url_org_id;
		let url_parent_id = getLocationParams(newUrl.href,'parent_id');
		parent_id.value=url_parent_id;
		let url_lever_id = getLocationParams(newUrl.href,'lever_id');
		lever_id.value=url_lever_id;

		
		
	
		//批量操作
		// const handleBatchClick= async (e)=>{
		//    //console.log(e)
		//    if(e.type=="shareauth"){
        //        router.push({path:'/Permission/userPermission',params:{id:[5,7,8]}})



		//    }
	  
		// }

		const handleBatchClick: MerakXTableInstance["batchClick"] = async ({ type, mode, selectedKeys }) => {
		//console.log(selectedKeys)
		const selectedKeysString=JSON.stringify(selectedKeys)
		switch (type) {
			case "shareauth":
			//this.$router.push({ name: 'Home', params: { id: 123 }})
			router.push({
				path:'/Permission/userPermission',
				query:{'id':selectedKeysString,'type':'batch'}, 
			})
			return {
				
			};
			default:
			return;
		}
		};
	
	
		//#region 搜索表单
		const search_val = ref("");
		const searchFn=(e)=>{
			//console.log(e)
			// e.searchVal
			state.params.key_words=e.search;
		}
	
	
		const nodeChange=(data:any)=>{
			//console.log(data)
			// 构建新的URL
			const newUrl = new URL(window.location.href);
			////console.log(newUrl)
		
			newUrl.searchParams.set('lever_id', data.level);
			lever_id.value= data.level;
			newUrl.searchParams.set('org_id', data.org_id);
			org_id.value= data.org_id;

			newUrl.searchParams.set('parent_id', data.parent_id??0);
			parent_id.value= data.parent_id;
			


	







			// 使用pushState更新浏览器历史记录
			window.history.pushState({}, '', newUrl.toString());
	
			search_val.value="";
	
			//console.log(search_val.value)
			tableRef.value?.reloadData();
		}
	
		//#endregion
	


		//跳转到分配权限详情页面
		const godetail=(row)=>{
			
			router.push({path:'/Permission/userPermission',query:{id:row.user_id,'type':'user',name:row.employee_name}})
		}


		


	

	

	
	
		//权限数据
		// let authArr=ref({});
		let authArr=reactive({});
	
		//列表内容展示区
		const handleQueryData: MerakXTableInstance["queryData"] = async ({ page, sorts, filters, from }) => { 
			const params: Record<string, any> = {}; 
			if (!!page) {
				//console.log(params)
				if(org_id.value==false){
		
					org_id.value=''
				}
				if(lever_id.value==false){
		
					lever_id.value=''
				}
			
				//console.log(lever_id.value)
				//console.log(from)


				
			   
	
	
				Object.assign(params, { ...page ,lever_id:lever_id.value,org_id:org_id.value});
		 
				
			}
			//console.log(from)
			for(let key of Object.keys(from)) {
				if (!!from[key]) {
					params[key]=from[key]
				}
			}
			return await permissionAuthListApi(params).then(res => {
				//console.log(res)
				if (res.code == ResultEnum.SUCCESS) {
					let data = res.data;
					for (let index = 0; index < data.table_data.list.length; index++) {
							const element = data.table_data.list[index];
							// //console.log(element)
							if (element.access_status == 1) {
								element.access_status=false;
							}else{
								element.access_status=true;
							}
							

					}
					//console.log(data)
				
					Object.assign(authArr,data.auth_list)
					Object.assign(persondata,data.UserTreeList)



					
	
					const { table_data, language } = data as { table_data: Record<string, any>; language: Record<string, any> };
				
					return table_data;
				}
			})
	
		};
	
	
	 
		//表头信息
		const handleQueryColumns: MerakXTableInstance["queryColumns"] = async () => {
			return await permissionAuthHeaderApi().then(res => {
				if (res.code == ResultEnum.SUCCESS) {
	
	
				  
	
					let data = res.data as MerakXTableQuery.Columns;
					// const { pageSize, columns } = data as { pageSize: number; columns: MerakXTableColumn[] };
					for (let index = 0; index < data.columns.length; index++) {
							const element = data.columns[index];
							// //console.log(element)
							if (element.field == "access_status") {
								element["slots"] = { default: "access_status_slots" }
							}
							

						}
						// //console.log(data)
	
					  //获取表头后使用tableid 获取搜索方案
					  queryFilterOptions(data);
	
					state.columns = data.columns;
					return data;
				}
			})
		};
	
	
	
	
	
	
	
	
	
	
	
	
	
	// 获取高级搜索方案
	const queryFilterOptions = async data => {
	  searchbar.value.getPlanList(data.table_id);
	  // 初始化接口需要传入队列 loading 暴露的 id
	};
	
		// 高级搜索表单
	const ruleFormRef = ref<FormInstance>();
	const searchform = ref({
	  org_company: {
		label: "公司",
		value: "",
		type: "select",
		options: [
		  { label: "北京企发", value: 1 },
		  { label: "米格速达", value: 2 },
		  { label: "新世纪农业", value: 3 }
		]
	  },
	  org_department: {
		label: "部门",
		value: "",
		type: "select",
		options: [
		  { label: "物流", value: 1 },
		  { label: "研发", value: 2 },
		  { label: "销售", value: 3 }
		]
	  },
	  job_nature: {
		label: "工作性质",
		value: "",
		type: "select",
		options: [
		  { label: "全职", value: 1 },
		  { label: "兼职", value: 2 }
		]
	  },
	  status: {
		label: "状态",
		value: "",
		type: "select",
		options: [
		  { label: "在职", value: 1 },
		  { label: "试用期", value: 2 }
		]
	  }
	});
	
	//高级搜索模态
	const searchbar = ref();
	
	
	
	
	const state = reactive < {
			params: Record < string, any>;
			columns: MerakXTableColumn[];
		} > ({
			params: {
				key_words: ""
			},
			columns: []
		}); 
	
	
	
	
	//点击取消按钮关闭高级搜索模态框
	const closeModal = () => {
	  searchbar.value.modalHide();
	  searchbar.value.clear();
	};
	
	//打开搜索方案弹出
	const showPlanModal = () => {
	  searchbar.value.showPlanModal();
	};
	
	//搜索表单提交
	const searchSubmitForm = async (formEl: FormInstance | undefined) => {
	  state.params =  { ...searchbar.value.formParams("value") };
	  searchbar.value.clear();
	  searchbar.value.clear();
	  searchbar.value.modalHide();
	};
	
	
	//触发了快速搜索或者搜索方案
	const searchBarPost = params => {
	// //console.log(params)
	  let postParams = { ...params.params,  search: params.search  };
	  state.params = postParams;
	};
	
	
	
	</script>
	
	<style scoped lang="scss">
	:deep(.merak-table-body){
		.el-switch__core .el-switch__inner .is-text{
            margin-left: 2px;
		 }
	}
         
		.translation {
			/* display: flex;
			flex-direction: column;
			width: 100%;*/
			height: 100%;
	
	
		}
		.translation_card {
			display: flex;
			flex-direction: column;
			width: 100%;
			height: 100%;
	
			.table_main {
				/* display: flex;
				flex-direction: column;
				width: 100%;
				height: 100%; */
				flex: auto;
				min-height: 0;
			}
		}
	
		.translationPad {
			padding: 15px;
		}




		
.personbox {
    display: flex;
}
.personall {
    margin-top: 20px;
    height: 360px;
    overflow-y: auto;
}
.treeR {
    border-left: 1px solid #DCDFE6;
}
.checkedperson_ever:hover {
    background: var(--el-color-primary-light-9);
}
.treeRtit{
  padding:10px;
 font-weight:bold;
}
.treeL {
    padding-right: 20px;
}
.treeR {
    padding-left: 10px;
}
.treeL, .treeR {
    width: 50%;
}
.checkedpersons {
    height: 373px;
    overflow-y: auto;
}
.checkedperson_ever {
    line-height: 34px;
    cursor: pointer;
    padding: 0 10px;
    font-size: 14px;
}
.checkedperson_ever svg {
    float: right;
    font-size: 16px;
    padding-top: 9px;
    color: var(--el-color-danger);
	
}
.descriptions-box{
    min-width: 0;
}



	</style>